<template>
    <el-dialog :visible="visible"
               title="Sync Integrations"
               :close-on-click-modal="false"
               :close-on-press-escape="false"

               @close="handleClose"
               class="intergrations-get-started"
               width="60%">
      <div class="contantTip">
        <span class="integration_pagetext_box el-icon-warning-outline"></span>
        <div class="rightContant">
          <div style="color:#a2413a">Dear {{user}}</div>
          <p style="color:#a2413a">Welcome back! Your integration data sync were paused due to the inactivity for more than 30 days, to continue use MSPbots, please click the button to resume the data sync. Without data sync, the dashboards and bots won't working properly.</p>
          <p style="color:#a2413a">Note: Data sync could take from a couple of minutes to a couple of hours depends on the amount of data needs to be synced</p>

        </div>
      </div>
      <div class="data_connent_content">
        <el-card shadow="never"
                 class="aui-card--fill"
                 v-loading="loading"
                 style="border:none;position:relative">
          <el-collapse v-model="checkedState">
            <el-collapse-item
                              name="1"
                              :title="$t('custom.connector.haveauthorized')">
              <template slot="title">
                <i class="icon-left-authorized"></i>
                <span class="api-manager-title">{{$t('custom.connector.connected')}}</span>
              </template>
              <ConnectTipItem v-for="(value,key) in haveAuthorized"
                        :key="key"
                        :itemInfo="value"
                        @startStop="startStop" />
            </el-collapse-item>
            <el-collapse-item :title="$t('custom.connector.unauthorized')"
                              name="2"
                              ref="wait-wrapper"
                              id="wait-wrapper">
              <template slot="title">
                <i class="icon-left-unAuthorized"></i>
                <span class="api-manager-title">{{$t('custom.connector.waitingtobeconnected')}}</span>
              </template>
              <div>
                <ConnectTipItem v-for="(value,key) in unAuthorized"
                        :key="key"
                        :itemInfo="value"
                        @startStop="startStop" />
              </div>
            </el-collapse-item>
            <el-collapse-item
                              :title="$t('custom.connector.others')"
                              name="3">
              <template slot="title">
                <i class="icon-left-other"></i>
                <span class="api-manager-title">{{$t('custom.connector.otheravailableintegrations')}}</span>
              </template>
              <ConnectTipItem v-for="(value,key) in other"
                        :key="key"
                        :itemInfo="value"
                        @startStop="startStop" />
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>

      <template slot="footer">
      </template>
    </el-dialog>

</template>

<script>
import ConnectTipItem from './connectTipItem.vue'
import { unionIntegrationList } from '@/components/storybook/utilties/tools'
export default {
  data () {
    return {
      user: this.$store.state.user.name,
      connectorInfo: {},
      checkedState: ['1', '2', '3'],
      visible: false,
      loading: false
    }
  },
  props: {
    seeDialog: {
      type: String,
      default: null
    }
  },
  components: {
    ConnectTipItem
  },

  computed: {
    // visible () {
    //   return this.$store.state.user.integrationEventType === 'no_login_30day_off'
    //   // return false
    // },
    haveAuthorized () {
      let tempObj = {}
      let last = {}
      tempObj = this.orderByLastTimeAsc()
      for (const key in tempObj) {
        if (tempObj[key]['sync'].group === 1) {
          last[key] = tempObj[key]
        }
      }
      return last
    },
    unAuthorized () {
      let tempObj = {}
      let last = {}
      tempObj = this.orderByLastTimeAsc()
      for (const key in tempObj) {
        if (tempObj[key]['sync'].group === 2) {
          last[key] = tempObj[key]
        }
      }
      return last
    },
    other () {
      let tempObj = {}
      let last = {}
      tempObj = this.orderByLastTimeAsc()
      for (const key in tempObj) {
        if (tempObj[key]['sync'].group === (null || 3)) {
          tempObj[key]['sync']['errorMsg'] = ''
          tempObj[key]['sync']['lastTime'] = null
          last[key] = tempObj[key]
        }
      }
      return last
    }
  },
  watch: {
    seeDialog: {
      handler (val) {
        if (val === 'no_login_30day_off') {
          this.getConnectorInfo()
          this.visible = true
        }
      },
      immediate: true
    }
  },

  methods: {
    getConnectorInfo () {
      this.loading = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.taskManager.getConnectorInfo(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          for (var key1 in res.data) {
            if (!res.data[key1]) {
              delete res.data[key1]
            }
          }
          let mapObj = res.data
          let tempList = []
          for (let key in mapObj) {
            if (mapObj[key].sync.group) {
              tempList.push({
                name: mapObj[key].name,
                subjectCode: mapObj[key].sync.subjectCode,
                status: mapObj[key].sync.status,
                group: mapObj[key].sync.group
              })
            }
          }
          let connectorInfoList = []
          let tempArrayList = []
          tempArrayList = unionIntegrationList(tempList, 'subjectCode')
          for (let i = 0; i < tempArrayList.length; i++) {
            const element = tempArrayList[i].subjectCode
            for (let key in mapObj) {
              if (key === element) {
                connectorInfoList.push(mapObj[key])
              }
            }
          }
          this.connectorInfo = connectorInfoList
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    async startStop (data) {
      const { get } = this._
      const { controlTdDataSync } = this.$interface.taskManager
      try {
        this.syncLoading = true
        const params = {
          subjectCode: get(data, 'sync.subjectCode'),
          tenantId: this.$store.state.user.tenantCode,
          onoff: data.onoff === 'ON' ? 'OFF' : 'ON',
          creator: this.$store.state.user.id
        }
        let { data: response } = await controlTdDataSync(params)
        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        // this.onoff = get(response, 'data')
        this.getConnectorInfo()
        // Component.$emit('getConnectorConfig')
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.syncLoading = false
      }
    },
    orderByNameAsc () {
      const dadaList = this._.orderBy(this._.toArray(this.connectorInfo), 'name', 'asc')
      const returnData = {}
      dadaList.forEach(item => {
        returnData[item.sync.subjectCode] = item
      })
      return returnData
    },
    orderByLastTimeAsc () {
      var _self = this
      const returnData = {}
      const dadaList = _self._.orderBy(_self._.toArray(_self.connectorInfo), 'sync.lastTimeLong', 'asc')
      dadaList.forEach(item => {
        returnData[item.sync.subjectCode] = item
      })
      return returnData
    },
    handleClose () {
      this.$store.state.user.integrationEventType = null
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.intergrations-get-started {
  .el-collapse {
    border: 0;
  }
  .content_data_connector {
    box-shadow: 0px 0px 0px 0px #f0f0f0 !important;
  }
  .el-collapse-item__header {
    border: 0;
  }
  .el-dialog__header {
    padding: 15px 16px 0 15px !important;
  }
  .el-dialog__body {
    padding: 16px !important;
    .contantTip {
      display: flex;
      justify-content: flex-start;
      padding: 8px;
      background: #fff1f0;
      border-radius: 4px;
      .integration_pagetext_box {
        display: inline-block;
        width: 22px;
      }
      .el-icon-warning-outline::before {
        font-size: 14px;
        color: red;
      }
      .rightContant {
        margin: 0;
        .intgegration_page_text {
          color: red;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }
    .connectTipItem {
      background: #f0f0f0;
      border-radius: 2px;
      padding: 10px;
    }
  }

  .el-dialog__wrapper {
    background: rgba(0, 0, 0, 0.2);
  }
  .data_connectors {
    ::v-deep .el-input {
      width: 100% !important;
    }
    .aui-card--fill {
      min-height: 100px;
      border: null;
    }
    ::v-deep .el-card__body {
      padding: 0 !important;
    }
  }
 .data_connent_content {
     .api-manager-title {
        font-size: 16px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.75);
        line-height: 22px;
      }
      .icon-left-authorized {
  // margin-left: 38px;
  margin-right: 13px;
  width: 20px;
  height: 20px;
  background-image: url("#{$--ossLink}/app/connector/connected.png");
  background-size: 20px;
}

.icon-left-unAuthorized {
  // margin-left: 38px;
  margin-right: 13px;
  width: 20px;
  height: 20px;
  background-image: url("#{$--ossLink}/app/connector/wait_connecting.png");
  background-size: 20px;
}

.icon-left-other {
  // margin-left: 38px;
  width: 20px;
  height: 20px;
  margin-right: 13px;
  background-image: url("#{$--ossLink}/app/connector/others.png");
  background-size: 20px;
}
.el-collapse-item ::v-deep .el-collapse-item__content {
  padding-bottom: 0 !important;
}
 ::v-deep .el-collapse-item__wrap {
        background: #f0f0f0;
        border-radius: 2px;
        padding: 10px;
      }

}

}

</style>
